import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, message, Popconfirm, TreeSelect, Select } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import { queryRule, updateRule, addRule, removeRule } from './service';
import { transTitle, handleReturnArray } from '@/utils/utils';
import FormItem from 'antd/lib/form/FormItem';
/**
 * 添加节点
 * @param fields
 */

const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');

  try {
    await addRule({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 * @param fields
 */

const handleUpdate = async (fields) => {
  const hide = message.loading('正在配置');

  try {
    await updateRule(fields);
    hide();
    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};
/**
 *  删除节点
 * @param selectedRows
 */

const handleRemove = async (payload, actionRef) => {
  const hide = message.loading('正在删除');
  try {
    await removeRule(payload);
    hide();
    message.success('删除成功，即将刷新');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [createEditModalVisible, handleEditModalVisible] = useState(false);
  const [FormValues, setFormValues] = useState({});
  const actionRef = useRef();
  const [treeValue, handleTreeValue] = useState();
  const [menuValues, setMenuValues] = useState([]);
  const [initCycle, setInitCycle] = useState();
  const createFormRef = useRef();
  const [row, setRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const TreeOnChange = (value) => {
    handleTreeValue(value);
  };
  const handleQueryMenu = async () => {
    try {
      const response = await queryRule({});
      const { data } = response;
      transTitle(data);
      setMenuValues(data);
      return true;
    } catch (error) {
      return false;
    }
  };
  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      valueType: 'textarea',
      hideInForm: true,
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '父级',
      dataIndex: 'parentId',
      hideInTable: true,
      hideInSearch: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <FormItem label={false}>
            <TreeSelect
              showSearch
              // style={{ width: '400px' }}
              value={treeValue}
              dropdownStyle={{ maxHeight: 800, overflow: 'auto' }}
              placeholder="请选择父级"
              allowClear
              treeDataSimpleMode
              treeData={menuValues}
              treeNodeFilterProp="title"
              treeNodeLabelProp="title"
              onChange={TreeOnChange}
            />
          </FormItem>
        );
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '父级为必填项',
          },
        ],
      },
    },

    {
      title: '名称',
      dataIndex: 'name',
      // tip: '规则名称是唯一的 key',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '名称为必填项',
          },
        ],
      },
    },
    {
      title: '类型',
      dataIndex: 'type',
      valueEnum: {
        1: {
          text: '省份',
          status: 'Processing',
          value: 1,
        },
        2: {
          text: '市',
          status: 'Success',
          value: 2,
        },
        3: {
          text: '县',
          status: 'Error',
          value: 3,
        },
        4: {
          text: '街道办',
          status: 'Default',
          value: 4,
        },
        5: {
          text: '社区',
          status: 'Default',
          value: 5,
        },
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '类型为必填项',
          },
        ],
      },
      // hideInTable: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <FormItem label={false} name="type">
            <Select placeholder="请选择">
              {handleReturnArray(item.valueEnum, 6).map((item_in, index) => {
                if (item_in) {
                  return (
                    <Select.Option key={index} value={item_in.value}>
                      {item_in.text}
                    </Select.Option>
                  );
                }
              })}
            </Select>
          </FormItem>
        );
      },
    },
    {
      title: '区域编码',
      dataIndex: 'code',
      // tip: '规则名称是唯一的 key',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '区域编码为必填项',
          },
        ],
      },
      hideInSearch: true,
    },
    {
      title: '区域负责人',
      dataIndex: 'contacts',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '区域负责人联系方式',
      dataIndex: 'tel',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '详细地址',
      dataIndex: 'address',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleQueryMenu();
              handleEditModalVisible(true);
              setFormValues(record);
              setInitCycle(record.type);
            }}
          >
            修改
          </a>
          <Divider type="vertical" />
          <Popconfirm
            placement="top"
            title="确定要删除吗?"
            onConfirm={() => {
              handleRemove(record.id, actionRef);
            }}
            okText="Yes"
            cancelText="No"
          >
            <a onClick={() => {}}>删除</a>
          </Popconfirm>
        </>
      ),
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="区域列表"
        actionRef={actionRef}
        rowKey="id"
        bordered
        search={{
          labelWidth: 120,
        }}
        bordered
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={() => {
              handleQueryMenu();
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新增
          </Button>,
        ]}
        options={false}
        request={(params, sorter, filter) => queryRule({ ...params, sorter, filter })}
        beforeSearchSubmit={(payload) => {
          const { type } = payload;
          payload.parent = true;
          if (type && type != 1) {
            delete payload.parent;
          }
          return payload;
        }}
        pagination={false}
        columns={columns}
        rowSelection={false}
      />
      <CreateForm
        title="添加区域"
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      >
        <ProTable
          onSubmit={async (value) => {
            const success = await handleAdd(value);

            if (success) {
              handleModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          columns={columns}
        />
      </CreateForm>
      <CreateForm
        title="修改区域"
        onCancel={() => handleEditModalVisible(false)}
        modalVisible={createEditModalVisible}
      >
        <ProTable
          onSubmit={async (value) => {
            value.version = FormValues.version + 1;
            value.id = FormValues.id;
            const success = await handleUpdate(value);

            if (success) {
              handleEditModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          formRef={createFormRef}
          onLoad={(() => {
            if (createFormRef.current) {
              createFormRef.current.setFieldsValue({
                type: initCycle,
              });
            }
          })()}
          form={{ initialValues: FormValues }}
          rowKey="id"
          bordered
          type="form"
          columns={columns}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
